/*
 * drag verify - custom version
 * author Feng_zhenjie@126.com
 * date 2016-09-18
 */

// create modal tips style
/*(function() {
	if (document.getElementById('dragCustom_css') == null) {
		var link = document.createElement('link');
		link.id = "dragCustom_css";
		link.setAttribute("rel", "stylesheet");
		link.setAttribute("type", "text/css");
		link.setAttribute("href", "/public/home/plug/drag/drag.custom.css");
		document.getElementsByTagName("head")[0].appendChild(link);
	}
})();*/

function closeDragVerify(_id) {
	if(typeof(dragBox) == 'object') {
		document.getElementById(_id).removeChild(dragBox);
	}
}

function showDragVerify(opt) {
	var opt = opt ? {
		'sdv_createbox': opt.sdv_createbox || '',
		'sdv_callback': opt.sdv_callback || function() {}
	} : {
		'sdv_createbox': '',
		'sdv_callback': function() {}
	};
	closeDragVerify(opt.sdv_createbox);
	var div = document.createElement('div');
	div.id = 'dragBox';
	div.className = "pie";
	div.onselectstart = new Function("return false");
	var ele = '';
	ele += '<div id="dragBoxClose"></div>';
	ele += '<div id="drag">';
	ele += '<div id="drag_bg"></div>';
	ele += '<div id="drag_text">拖动滑块验证</div>';
	ele += '<div id="handler" class="handler_bg"></div>';
	ele += '</div>';
	div.innerHTML = ele;
	document.getElementById(opt.sdv_createbox).appendChild(div);
	initDragVerify(opt);
}

function initDragVerify(opt) {
	dragBoxClose.onclick = function() { closeDragVerify(opt.sdv_createbox) };

	var handler = document.getElementById('handler');
	var drag = document.getElementById('drag');
	var maxWidth = drag.clientWidth - handler.clientWidth;
	var disappear, opacityValue = 100;

	handler.onmousedown = function(e) {
		var e = e || window.event;
		var startX = e.clientX;
		document.onmousemove = function(e) {
			var e = e || window.event;
			var nowX = e.clientX - startX;
			if(nowX <= maxWidth && nowX >= 0) {
				handler.style.left = nowX + 'px';
				drag_bg.style.width = nowX + 'px';
			}
			if(nowX > maxWidth) {
				handler.style.left = maxWidth + 'px';
				drag_bg.style.width = maxWidth + 'px';
			}
		}
		document.onmouseup = function() {
			document.onmousemove = null;
			document.onmouseup = null;
			if(handler.offsetLeft < (maxWidth - 4)) {
				handler.style.left = 0;
				drag_bg.style.width = 0;
			} else {
				dragBoxClose.onclick = function() {};
				handler.className = 'handler_ok_bg';
				handler.style.left = maxWidth + 'px';
				drag_bg.style.width = maxWidth + 'px';
				drag_text.innerHTML = '验证通过';
				drag_text.style.color = '#FFFFFF';
				setTimeout(function() {
					// disappear = setInterval(function() {
					// 	dragBox.style.filter = 'alpha(opacity=' + (opacityValue -= 10) + ')';
					// 	if(opacityValue <= 0) {
					// 		clearInterval(disappear);
					// 		// closeDragVerify(opt.sdv_createbox);
							opt.sdv_callback();
					// 	}
					// }, 50);
				}, 300);
			}
		}
	}
}
